from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from datetime import datetime
import uuid

from ..database import get_db
from ..models.user import User
from ..models.chat_history import ChatHistory
from ..auth.auth import get_current_active_user
from ..config import settings

router = APIRouter()

class ChatMessage(BaseModel):
    message: str
    session_id: str = None
    message_type: str = "chat"

class ChatResponse(BaseModel):
    id: int
    session_id: str
    user_message: str
    ai_response: str
    message_type: str
    created_at: datetime
    
    class Config:
        from_attributes = True

class DifyConfig(BaseModel):
    iframe_url: str = None
    api_url: str = None
    api_key: str = None

@router.post("/send", response_model=ChatResponse)
async def send_message(
    chat_msg: ChatMessage,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """发送聊天消息"""
    # 如果没有提供session_id，生成一个新的
    if not chat_msg.session_id:
        chat_msg.session_id = str(uuid.uuid4())
    
    # TODO: 这里应该调用Dify API获取AI回复
    # 现在先返回一个模拟回复
    ai_response = f"这是对'{chat_msg.message}'的AI回复。当前用户：{current_user.username}"
    
    # 保存聊天记录
    chat_history = ChatHistory(
        session_id=chat_msg.session_id,
        user_message=chat_msg.message,
        ai_response=ai_response,
        message_type=chat_msg.message_type,
        user_id=current_user.id
    )
    
    db.add(chat_history)
    db.commit()
    db.refresh(chat_history)
    
    return chat_history

@router.get("/history", response_model=List[ChatResponse])
async def get_chat_history(
    session_id: str = None,
    limit: int = 50,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取聊天历史"""
    query = db.query(ChatHistory).filter(ChatHistory.user_id == current_user.id)
    
    if session_id:
        query = query.filter(ChatHistory.session_id == session_id)
    
    chat_history = query.order_by(ChatHistory.created_at.desc()).limit(limit).all()
    return chat_history

@router.get("/sessions")
async def get_chat_sessions(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户的聊天会话列表"""
    sessions = db.query(ChatHistory.session_id).filter(
        ChatHistory.user_id == current_user.id
    ).distinct().all()
    
    return [{"session_id": session[0]} for session in sessions]

@router.get("/config", response_model=DifyConfig)
async def get_dify_config():
    """获取Dify配置"""
    return DifyConfig(
        iframe_url=settings.DIFY_IFRAME_URL,
        api_url=settings.DIFY_API_URL,
        api_key=settings.DIFY_API_KEY
    )

@router.delete("/history/{session_id}")
async def delete_chat_session(
    session_id: str,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除聊天会话"""
    deleted_count = db.query(ChatHistory).filter(
        ChatHistory.session_id == session_id,
        ChatHistory.user_id == current_user.id
    ).delete()
    
    db.commit()
    
    if deleted_count == 0:
        raise HTTPException(status_code=404, detail="会话不存在")
    
    return {"message": f"已删除 {deleted_count} 条聊天记录"} 